package middleware

import (
	"net/http"
	"myblog/configs"
	"myblog/utils"
	
	"github.com/gin-gonic/gin"
)

// AuthMiddleware 管理员认证中间件
func AuthMiddleware(cfg *configs.Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := utils.ExtractToken(c)
		if tokenString == "" {
			c.Redirect(http.StatusFound, "/admin/login")
			c.Abort()
			return
		}
		
		claims, err := utils.ValidateJWT(tokenString, cfg.JWT.Secret)
		if err != nil || claims.Username != cfg.Auth.Username {
			c.Redirect(http.StatusFound, "/admin/login")
			c.Abort()
			return
		}
		
		// 将用户名添加到上下文
		c.Set("username", claims.Username)
		c.Next()
	}
}